/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-01-12 10:41:23
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-05-20 15:21:48
 * @FilePath: \report-h5\src\utils\WXSdk.ts
 */
import wx from 'weixin-js-sdk-ts'
import { appId } from './config'
import { getdWeixinSdkConfig } from '@/apis/wx'
import { ref, watchEffect } from 'vue'
import { CxlMessage } from '@/components/message'
import CompressImage from './compressImage'

export interface WxConfig {
    appId?: string // 必填，公众号的唯一标识
    timestamp: number // 必填，生成签名的时间戳
    nonceStr: string // 必填，生成签名的随机串
    signature: string // 必填，签名，见附录1
    jsApiList?: wx.jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    openTagList?: wx.openTagList
}

interface PayConfig {
    timestamp: number
    nonceStr: string
    package: string
    signType: string
    paySign: string
}

interface ShareInterface {
    title: string
    desc: string
    link: string
    imgUrl: string
}

export function getBase64ImageSizeInKB(base64: string) {
    // Base64编码会增加约33%的数据大小
    let estimatedSize = (base64.length * 3) / 4

    // 对齐到8的倍数
    if (base64.length % 4 != 0) {
        estimatedSize += 3 - (base64.length % 4)
    }
    return Number(estimatedSize / 1024)
}

export class WeixinSDK {
    ready = ref(false)
    previewUrl = ''
    constructor() {}
    init = (config: WxConfig, callback: () => void) => {
        console.log('appId', appId)
        wx.config({
            debug: false,
            appId: appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData',
                'onMenuShareWeibo',
                'downloadImage',
                'uploadImage',
                'chooseWXPay',
                'chooseImage',
                'previewImage',
                'hideMenuItems',
                'showMenuItems'
            ],
            openTagList: []
        })

        wx.ready(() => {
            this.ready.value = true
            callback()
            console.log('ready')
        })

        wx.error(err => {
            console.log(err)
        })
    }
    upImg = (str: string) => {
        wx.uploadImage({
            localId: str,
            isShowProgressTips: 0,
            success: function (res: { serverId: string }): void {
                wx.downloadImage({
                    serverId: res.serverId,
                    isShowProgressTips: 0,
                    success: function (res: wx.Resouce): void {
                        throw new Error('Function not implemented.' + res)
                    }
                })
            }
        })
    }

    /**
     * 选择图片
     * @returns
     */
    onChooseImage = () => {
        return new Promise(resolve => {
            wx.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    console.log('选择图片', res)
                    this.previewUrl = res.localIds[0]
                    //const localIds = res.localIds // 返回选定照片的本地 ID 列表，localId可以作为 img 标签的 src 属性显示图片
                    wx.getLocalImgData({
                        localId: res.localIds[0],
                        success: r => {
                            resolve(r)
                        }
                    })
                },
                cancel: function (): void {
                    throw new Error('Function not implemented.')
                }
            })
        })
    }

    /**
     * 唤起支付
     * @returns
     */
    onChooseWXpay = (payConfig: PayConfig) => {
        return new Promise((resolve, reject) => {
            wx.chooseWXPay({
                timestamp: payConfig.timestamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
                nonceStr: payConfig.nonceStr, // 支付签名随机串，不长于 32 位
                package: payConfig.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: payConfig.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
                paySign: payConfig.paySign, // 支付签名
                success: function (res) {
                    // 支付成功后的回调函数
                    resolve(res)
                },
                cancel(res) {
                    //取消支付
                    reject(res)
                },
                fail(err) {
                    //支付失败
                    reject(err)
                }
            })
        })
    }
    //预览图片
    previewImage = () => {
        console.log('预览', this.previewUrl)
        wx.previewImage({
            current: this.previewUrl,
            urls: [this.previewUrl]
        })
    }
    //自定义分享
    share = () => {
        wx.updateAppMessageShareData({
            title: '这是一个我写的标题',
            desc: '这是描述这是描述这是描述这是描述这是描述这是描述这是描述',
            link: 'http://web.chexinlian.com/',
            imgUrl: 'http://web.chexinlian.com/png/icon_lsbg@3x-8eb45f24.png',
            success: () => {
                console.log('success')
            },
            cancel: () => {
                console.log('cancel')
            }
        })
    }
    //禁止传播分享
    disableShare = () => {
        watchEffect(() => {
            if (this.ready.value) {
                wx.hideMenuItems({
                    menuList: [
                        'menuItem:share:appMessage',
                        'menuItem:share:timeline',
                        'menuItem:share:qq',
                        'menuItem:share:weiboApp',
                        'menuItem:favorite',
                        'menuItem:share:facebook',
                        'menuItem:share:QZone'
                    ]
                })
            }
        })
    }
    ableShare = () => {
        wx.showMenuItems({
            menuList: [
                'menuItem:share:appMessage',
                'menuItem:share:timeline',
                'menuItem:share:qq',
                'menuItem:share:weiboApp',
                'menuItem:favorite',
                'menuItem:share:facebook',
                'menuItem:share:QZone'
            ]
        })
    }

    //出险报告分享
    shareReport = (params: ShareInterface) => {
        wx.updateAppMessageShareData({
            title: params.title,
            desc: params.desc,
            link: params.link,
            imgUrl: params.imgUrl,
            success: () => {
                console.log('success')
            },
            cancel: () => {
                console.log('cancel')
            }
        })
    }
    //维保车况报告分享
    shareReport2 = (params: ShareInterface) => {
        wx.updateAppMessageShareData({
            title: params.title,
            desc: params.desc,
            link: params.link,
            imgUrl: params.imgUrl,
            success: () => {
                console.log('success')
            },
            cancel: () => {
                console.log('cancel')
            }
        })
    }
    resetInit(callback = function () {}) {
        //获取微信sdk配置
        getdWeixinSdkConfig().then((res: any) => {
            if (res.data.value === 200) {
                this.init(
                    {
                        timestamp: res.data.data.timestamp,
                        nonceStr: res.data.data.nonceStr,
                        signature: res.data.data.signature
                    },
                    () => {
                        callback()
                    }
                )
            }
        })
    }
}

const useWeixinSdk = new WeixinSDK()

export default useWeixinSdk
